﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class FollowPlayer : MonoBehaviour
{
    public float minAng, maxAng;
    public Vector3 offsetToEye;
    public bool lookAtPlayer = true;
    public bool follow = true;

    private void Update()
    {
        Follow();
    }

    void Follow()
    {
        if (follow)
        {
            Vector3 pos = VRManager.manager.trackedObjectManager.eye.position;
            Vector3 eyeFA = Vector3.ProjectOnPlane(VRManager.manager.trackedObjectManager.eye.forward, Vector3.up).normalized;//眼的前方
            Vector3 eyeRA = Vector3.ProjectOnPlane(VRManager.manager.trackedObjectManager.eye.right, Vector3.up).normalized;//眼的右方
            Vector3 p2eA = Vector3.ProjectOnPlane(transform.position - VRManager.manager.trackedObjectManager.eye.position, Vector3.up).normalized;//到眼的方向
            Vector3 axi = p2eA;
            float a = SignedAngleBetween(eyeFA, p2eA, Vector3.up);
            if (a < minAng)
            {
                a = Mathf.Lerp(a, minAng, Time.deltaTime * 2);
                axi = Quaternion.AngleAxis(a, Vector3.up) * eyeFA;
            }
            else if (a > maxAng)
            {
                a = Mathf.Lerp(a, maxAng, Time.deltaTime * 2);
                axi = Quaternion.AngleAxis(a, Vector3.up) * eyeFA;
            }
            pos.y += offsetToEye.y;
            pos += axi * offsetToEye.x;
            pos += axi * offsetToEye.z;

            transform.position = pos;

            if (lookAtPlayer)
            {
                transform.forward = -p2eA;
            }
        }
    }

    public static float SignedAngleBetween(Vector3 a, Vector3 b, Vector3 n)
    {
        float angle = Vector3.Angle(a, b);
        float sign = Mathf.Sign(Vector3.Dot(n, Vector3.Cross(a, b)));
        float signed_angle = angle * sign;
        return signed_angle;
        //return (signed_angle <= 0) ? 360 + signed_angle : signed_angle;
    }
}
